﻿using UnityEngine;

namespace TouchFish.SingletonClass
{
    public class SingletonMono<T> : MonoBehaviour where T : UnityEngine.Component, ISingleton
    {
        private static object _lock = new object();
        private static T _instance;

        public static T Instance
        {
            get
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = FindObjectOfType<T>();
                        if (FindObjectsOfType(typeof(T)).Length > 1)
                        {
                            Debug.LogError("[Singleton] Something went really wrong " +
                                           " - there should never be more than 1 singleton!" +
                                           " Reopening the scene might fix it.");
                        }
                        if (_instance != null)
                            _instance.OnSingletonInit();
                    }
                    if (_instance == null)
                    {
                        Debug.LogWarning("there is no this componet in scene, we will create one");
                        _instance = new GameObject("(singleton) " + typeof(T).ToString()).AddComponent<T>();

                        if (_instance != null)
                            _instance.OnSingletonInit();
                    }
                    return _instance;
                }
            }
        }

        private void Awake()
        {
            OnInitOrAwake();
        }

        protected virtual void OnInitOrAwake()
        {
            Debug.Log("OnInitOrAwake");
        }
    }
}